#!/usr/bin/env python
#-*- coding:utf-8 -*-

'''
Created on 2011-12-15

@author: zhangchong
'''


import sys
import os
import string
import Config
import time  
import commands

def splitHour(date, type="all"):
    
    starttime = time.time()
    
    type = str(type)
    date = str(date)
    
    if(type != "access" and type != "statis"):
        splitHour(date, "statis")
        splitHour(date, "access")
        return
    
    print date + " " + type
    srcLog = Config.SaveLogDir + type + "_log_" + date + "_sort"
    
    if(not os.path.exists(srcLog)):
        cmd = "tar zxvf " + srcLog + ".tar.gz -C " + Config.SaveLogDir
        print cmd
        result = os.popen(cmd)
        result = result.read()
        print result
 
    
    cmd = Config.gawk + " -v date=\"" + date + "\" -v output=\"" + Config.SaveLogDir + date + "/\" -v filename=\"" + type + "\" -f " + Config.ScriptsDir + "SplitHour.awk " + srcLog
    print cmd
    result = os.popen(cmd)
    result = result.read()
    print result
    
    cmd = "rm -fr " + srcLog
    print cmd
    result = os.popen(cmd)
    result = result.read()
    print result
    
    endtime = time.time()
    print "splitHour " + type + " Run times:" + str(int((endtime - starttime))) 
    

def splitPid(date):
    
    starttime = time.time()
    
    date = str(date)
    cmd = "rm -fr " + Config.SaveLogDir + date[0:4] + "/" + date[4:6] + "/" + date[6:8] 
    print cmd
    result = os.popen(cmd)
    result = result.read()
    print result
    for i in range(0, 24):
        cmd = Config.ScriptsDir + "hash_file.sh  " + Config.SaveLogDir + date + " " + Config.SaveLogDir[0:len(Config.SaveLogDir) - 1] + " " + date + " " + "%02d" % i
        print cmd
        (status, result) = commands.getstatusoutput(cmd)
        print status, result
        
    cmd = "rm -fr " + Config.SaveLogDir + date + "/"
    print cmd
    result = os.popen(cmd)
    result = result.read()
    print result
    
    
    endtime = time.time()
    print "splitPid Run times:" + str(int((endtime - starttime))) 
              
        
def split(date, type="all"):
    splitHour(date, type)
    splitPid(date)
    

if __name__ == "__main__":

    argv = sys.argv
    cpdate = argv[1]
    cptype = "all"
    try:
        cptype = argv[2]
    except:
        cptype = "all" 
    split(cpdate, cptype)
    
    
    
    
    
